<?php
/**
 * common repository file Created by PhpStorm.
 * User: yang
 * Date: 2020/06/15
 */

namespace Common\Repository;

use Common\Model\Forum;
use DB;

class ForumRepository extends BaseRepository
{
    public function baseModel()
    {
        return new Forum();
    }

    /**
     * 获取置顶列表
     * @return array
     */
    public function extendGetTop()
    {
        return Forum::with(['get_user', 'get_type'])
            ->where(['is_top' => 1, 'status' => 0])
            ->withCount(['get_comment'])
            ->orderBy('updated_at', 'desc')
            ->limit(5)
            ->get()
            ->toArray();
    }

    /**
     * 获取列表数据-含分页
     * @param array $arr_option
     * @return mixed
     */
    public function extendGetList($arr_option = [])
    {
        $model = new Forum();
        if ($arr_option['order']['key'] == 'comment') {
            $model = $model->orderBy('get_comment_count', $arr_option['order']['value']);
        } else {
            $model = $model->orderBy($arr_option['order']['key'], $arr_option['order']['value']);
        }
        return $model->with($arr_option['with'])
            ->where($arr_option['where'])
            ->orWhere(function ($query) use ($arr_option) {
                if (!empty($arr_option['orWhere'])) {
                    $query->where($arr_option['orWhere']);
                }
            })
            ->withCount($arr_option['withCount'])
            ->orderBy('id', 'dsc')
            ->paginate($arr_option['limit'])
            ->toArray();
    }

    /**
     * 字段自增1
     * @param $id
     * @param string $field
     * @param int $step
     * @return mixed
     */
    public function increaseNum($id, $field = 'views_num', $step = 1)
    {
        return Forum::where('id', $id)->increment($field, $step);
    }

    /**
     * 统计数量
     * @return mixed
     */
    public function extendCount()
    {
        $month = date("Y-m-d", strtotime("-1 month"));//一月前时间
        $data['month'] = Forum::where('created_at', '>', $month)->count();
        $data['total'] = Forum::count();

        return $data;
    }
}